package com.waypolice.manager.controller;

import com.waypolice.common.constant.BorrowConstant;
import com.waypolice.common.pojo.AppraisalItemResult;
import com.waypolice.common.pojo.TaotaoResult;
import com.waypolice.common.utils.DateTimeUtil;
import com.waypolice.common.utils.ReadProperties;
import com.waypolice.manager.component.AddressUploadThread;
import com.waypolice.manager.service.*;
import com.waypolice.pojo.CmsBorRegister;
import com.waypolice.pojo.UpmsUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.*;

/**
 * @Description 首页上部内容展示
 * @Author wangrang
 * @Date Created in 14:38 2019/4/23
 * @Modified By:
 */
@Controller
@Api(value = "首页展示", description = "首页上部内容展示")
@RequestMapping(value="/pcwindow")
public class FirstHomeAction {
    private static final Logger LOGGER = LoggerFactory.getLogger(FirstHomeAction.class);

    @Autowired
    private FirstHomeService firstHomeService;

    @Autowired
    protected UserService userService;

    @Autowired
    protected BorRegisterService borRegisterService;

    @Autowired
    private UpmsUserRoleService upmsUserRoleService;

    @Autowired
    private ArcAppraisalService arcAppraisalService;

    /**
     * @author:wr
     * @description 跳转到首页
     * @date:
     * @return
     */
    @ApiOperation(value = "首页")
    @RequestMapping("/dashboard")
    public String toDashboard(HttpServletResponse response, HttpServletRequest request){
        Map<String, String> countData = firstHomeService.homePageAllCountData();
        request.setAttribute("countData",countData);
        return "dashboard";
    }

    /**
     * @author:zyp
     * @description 获取消息列表
     * @date: 2019/4/24 13:52
     * @return 
     */
    @ApiOperation(value = "获取消息列表")
    @RequestMapping("/getMessageList")
    @ResponseBody
    public Object getMessageList(HttpServletResponse response, HttpServletRequest request){
        List<String> finalList = new ArrayList<>();
        Properties properties = ReadProperties.getProperties("activiti.properties");
        //获取当前登录人的账号
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        //后续获取用户对象
        List<UpmsUser> users = userService.findByName(username);
        UpmsUser user = new UpmsUser();
        if(users!=null&&users.size()>0){
            user = users.get(0);
        }
        //审核流程成功提醒
        List<CmsBorRegister> cmsBorRegisters = borRegisterService.selectAuditSuccessList(user.getUserId());
        for (CmsBorRegister cmsBorRegister : cmsBorRegisters){
            String auditMessage = properties.getProperty("auditMessage");
            String registerNum = cmsBorRegister.getRegisterNum();
            int taskType = cmsBorRegister.getTaskType();
            auditMessage = auditMessage.replace("registerNum",registerNum);
            switch (taskType){
                case BorrowConstant.AUDIT_TYPE_BORROW:
                    auditMessage = auditMessage.replace("activitiType","借阅");
                    break;
                case BorrowConstant.AUDIT_TYPE_RENEW:
                    auditMessage = auditMessage.replace("activitiType","续借");
                    break;
                    default:
                        auditMessage = auditMessage.replace("activitiType","检索");
            }
            finalList.add(auditMessage);
        }
        //检索/借阅即将到期提醒
        List<CmsBorRegister> expireCmsBorRegisters = borRegisterService.selectExpireList(user.getUserId());
        Date nowDate = null;
        try {
            nowDate = DateTimeUtil.getTime00();
            for (CmsBorRegister expireCmsBorRegister : expireCmsBorRegisters ){
                String expireMessage = properties.getProperty("expireMessage");
                String registerNum = expireCmsBorRegister.getRegisterNum();
                Date planReturnTime = expireCmsBorRegister.getPlanReturnTime();
                int taskType = expireCmsBorRegister.getTaskType();
                expireMessage = expireMessage.replace("registerNum",registerNum);
                switch (taskType){
                    case BorrowConstant.AUDIT_TYPE_RENEW:
                        expireMessage = expireMessage.replace("activitiType","续借");
                        break;
                    case BorrowConstant.AUDIT_TYPE_BORROW:
                        expireMessage = expireMessage.replace("activitiType","借阅");
                        break;
                    default:
                        expireMessage = expireMessage.replace("activitiType","检索");
                }
                //planReturnTime比nowDate大（晚）
                if(DateTimeUtil.thenTwoDate(nowDate,planReturnTime).equals("1")||DateTimeUtil.thenTwoDate(nowDate,planReturnTime).equals("0")){
                    expireMessage = expireMessage.replace("expireTime","即将到期");
                }else if(DateTimeUtil.thenTwoDate(nowDate,planReturnTime).equals("-1")){
                    expireMessage = expireMessage.replace("expireTime","已过期");
                }
                finalList.add(expireMessage);
            }
        } catch (ParseException e) {

        }
        //保密期限到期的档案，需提醒档案管理员鉴定
        TaotaoResult result = upmsUserRoleService.findUserRole(user.getUserId());
        if(result.getStatus() == 200){
            //是档案管理员，给他提示
            List<AppraisalItemResult> itemList = arcAppraisalService.selectAllNeedAppraisalArc();
            int size = itemList.size();
            String secretAppraisalMessage = properties.getProperty("secretAppraisalMessage");
            secretAppraisalMessage = secretAppraisalMessage.replace("arcNum",String.valueOf(size));
            finalList.add(secretAppraisalMessage);
        }
        //显示当前用户是否有挂接任务，若有挂接 查看当前状态 如果为空 则代表当前挂接正在执行，如果不为空 并且日期与在三天之内，则提示挂接完成
        String uploadMessage = "";
        if(AddressUploadThread.userUploadStatus.containsKey(user.getUsername())){
            Date date = AddressUploadThread.userUploadStatus.get(user.getUsername());
            if(date==null){
                uploadMessage = properties.getProperty("doingUpload");
            }else{
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_YEAR,3);
                Date standardDate = calendar.getTime();
                if(DateTimeUtil.thenTwoDate(nowDate,standardDate).equals("1")||DateTimeUtil.thenTwoDate(nowDate,standardDate).equals("0")){
                    uploadMessage = properties.getProperty("uploaded");
                }
            }
        }
        finalList.add(uploadMessage);
        return finalList;
    }

}
